const CONFIG = require('./config'),
    PERSONAL_PATH = './json/personal.json',
    CANDIDATE_PATH = './json/candidates.json';

/*-CREATE SERVER-*/
const express = require('express'),
    app = express();
app.listen(CONFIG.PORT, () => {
    console.log(`THE WEB SERVICE IS CREATED SUCCESSFULLY AND IS LISTENING TO THE PORT：${CONFIG.PORT}`);
});

/*-MIDDLE WARE-*/
//=> Implementing CROS cross-domain middleware
app.use((req, res, next) => {
    const { ALLOW_ORIGIN, CREDENTIALS, HEADERS, ALLOW_METHODS } = CONFIG.CROS;
    res.header("Access-Control-Allow-Origin", ALLOW_ORIGIN);
    res.header("Access-Control-Allow-Credentials", CREDENTIALS);
    res.header("Access-Control-Allow-Headers", HEADERS);
    res.header("Access-Control-Allow-Methods", ALLOW_METHODS);
    req.method === 'OPTIONS' ? res.send('CURRENT SERVICES SUPPORT CROSS DOMAIN REQUESTS!') : next();
});

//=>Middleware for SESSION operation
const session = require('express-session');
app.use(session(CONFIG.session));

//=> Parse all the contents of the POST request and the request body, convert the URL-ENCODED format into an object, and store it in the REQ.BODY attribute.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//=> Before all requests start, get the data in JSON, mount it on some properties of REQ, and later want to get, just read from the
const { readFile } = require('./utils/promiseFS');
app.use(async (req, res, next) => {
    try {
        req.personalDATA = JSON.parse(await readFile(PERSONAL_PATH));
        req.candidateDATA = JSON.parse(await readFile(CANDIDATE_PATH));
        next();
    } catch (e) {
        console.log(e);
    }
});

/*-ROUTE-*/
// Route takeover
//=>Route management and control in EXPRESS, for example: the requested API interface address is '/personal/xxx', go directly to the './routes/personal' module to executes code
app.use('/candidate', require('./routes/candidate'));
app.use('/personal', require('./routes/personal'));
app.use((req, res, next) => {
    res.status(404);
    res.send('NOT FOUND!');
});